import React, { Component } from 'react';
import { connect, } from 'react-redux';
import moment from 'moment';
import request from '../api/request'
import { getImgUrl } from '../utils/utils'

class RotatePlay extends Component {
    state = {
        startList: [], //初始化默认显示内容
        rotate: 0,     //滚动角度
    }

    local = {
        point: 0,      // 上一个滚动位置
        angle: 0       // 固定滚动角度步长
    }

    luckyDrawEnd = null

    componentDidMount() {
    }

    //模拟数据获取，具体参见yuanyang项目
    async Ajax_getcurrent() {
        const { user: { openid } } = this.props
        let res = await request.luckyDraw({ openid })
        if (res.data) {
            this.luckyDrawEnd = res.data[0]
            return res.data
        } else {
            alert(res.message)
        }
    }

    async Get_Angle() {
        let start = 3600; //默认滚动角度
        let { rotate } = this.state;
        let { startList } = this.props;
        let { point, angle } = this.local;
        let j = 360 / startList.length; //计算滚动步长角度
        let current = await this.Ajax_getcurrent();
        console.log(current)
        if (!current) return
        let id = startList.findIndex(d => d.id == current[0].id) //判断应该转到大角度
        let end = -(rotate + point * angle + start + j * id);//每次转动减去之前滚动的角度，使角度归位。
        this.local = { ...this.local, ...{ point: id, angle: j } };//给本地角度复值
        return end;
    }
    async Event_Click_Rotate(ev) {
        let start = await this.Get_Angle();
        if (!start) {
            return
        }
        this.setState({ rotate: start })
        window.setTimeout(() => {
            this.props.end()
            alert(this.luckyDrawEnd.title)
            this.setState({
                rotate: 0
            })
        }, 6000)
    }
    //初始化每个与元素位置
    renderli = () => {
        let { startList } = this.props;
        let h = 100 / startList.length;  //设置元素高度百分比
        let r = 1 / startList.length;   //获取单位元素弧度
        return startList.map((el, ind) => {
            return (
                <li style={{ transform: `rotate(${ind * r}turn)` }} key={ind}>
                    {el.describePic ? <img src={getImgUrl(el.describePic)} width="50" height="50" /> : null}
                    <span class={`ball ball-${ind % 2}`}></span>
                    <p>{el.title}</p>
                </li>
            )
        })
    }

    render() {
        let { rotate } = this.state;
        return <div className="m-rotatePlay">
            <ul refs="MrotateDom" className="m-rotateDom" style={{ transform: `rotate(${rotate}deg)`, transition: rotate == 0 ? '' : 'transform 6s ease' }}>
                {this.renderli()}
            </ul>
            <div className="m-rotatePoint-box">
                <span></span>
                <p className="m-rotatePoint" onClick={this.Event_Click_Rotate.bind(this)}>抽奖</p>
            </div>
        </div>
    }
}

export default connect(({ user, code, luckyDraw }) => ({ user, code, luckyDraw }))(RotatePlay);
